package net.liteheaven.dtimer.timer

import android.app.AlarmManager
import android.app.PendingIntent
import android.app.Service
import android.content.Context
import android.content.Intent
import android.os.Build

/**
 * Created by LiangYu on 2018/7/27.
 */
object AlarmManagerUtil {

    fun scheduleBroadcast(ctx: Context, id: Int, intent: Intent, delayMs: Long) : PendingIntent{
        val pendingIntent = PendingIntent.getBroadcast(ctx, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        schedulePendingIntent(ctx, pendingIntent, delayMs)
        return pendingIntent
    }

    fun scheduleActivity(ctx: Context, id: Int, intent: Intent, delayMs: Long) : PendingIntent{
        val pendingIntent = PendingIntent.getActivity(ctx, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        schedulePendingIntent(ctx, pendingIntent, delayMs)
        return pendingIntent
    }

    fun scheduleService(ctx: Context, id: Int, intent: Intent, delayMs: Long) : PendingIntent{
        val pendingIntent = PendingIntent.getService(ctx, id, intent, PendingIntent.FLAG_UPDATE_CURRENT)
        schedulePendingIntent(ctx, pendingIntent, delayMs)
        return pendingIntent
    }

    private fun schedulePendingIntent(ctx: Context, pendingIntent: PendingIntent, delayMs: Long) {
        val nextAlarmInMilliseconds = System.currentTimeMillis() + delayMs
        val alarmManager = ctx.getSystemService(Service.ALARM_SERVICE) as AlarmManager
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            // In SDK 23 and above, dosing will prevent setExact, setExactAndAllowWhileIdle will force
            // the device to run this task whilst dosing.
            alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, nextAlarmInMilliseconds,
                    pendingIntent)
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            alarmManager.setExact(AlarmManager.RTC_WAKEUP, nextAlarmInMilliseconds,
                    pendingIntent)
        } else {
            alarmManager.set(AlarmManager.RTC_WAKEUP, nextAlarmInMilliseconds,
                    pendingIntent)
        }
    }

    fun cancelPendingIntent(ctx: Context, pendingIntent: PendingIntent){
        val alarmManager = ctx.getSystemService(Service.ALARM_SERVICE) as AlarmManager
        alarmManager.cancel(pendingIntent)
    }
}